//
//  CIBNPlayController.m
//  CIBN
//
//  Created by ZNGOO on 16/7/19.
//  Copyright © 2016年 韦儒健. All rights reserved.
//

#import "CIBNPlayController.h"
#import "CIBNPlayHomeModel.h"
#import "CIBNEpisodeListModel.h"
#import "CIBNVideoModel.h"
#import "CIBNAVPlayerManager.h"
#import "InterfacOrientation.h"
#import "AppDelegate.h"
#import "CIBNPlayTitleCell.h"
#import "CIBNRelatedVideoModel.h"
#import "CIBNCellRelatedCell.h"
#import "CIBNActorCell.h"


static NSString * ActorCell = @"CIBNActorCell";
static NSString * titleCell = @"CIBNPlayTitleCell";
static NSString * relatedCell = @"CIBNCellRelatedCell";
@interface CIBNPlayController () <UICollectionViewDelegate, UICollectionViewDataSource>

/** 集合视图 */
@property (nonatomic,strong) UICollectionView * collectionView;

/** 分组名 */
@property (nonatomic,strong) UILabel * sectionLabel;

/** 播放页数据 */
@property (nonatomic,strong) CIBNAVPlayerManager * playManager;

/** 播放页数据 */
@property (nonatomic,strong) CIBNPlayHomeModel * playDataModel;

/** 视频数据 */
@property (nonatomic,strong) NSMutableArray * videoDataArray;

/** 喜欢数据 */
@property (nonatomic,strong) NSMutableArray * likeDataArray;

/** 全屏按钮 */
@property (nonatomic,strong) UIButton * fullScreenBtn;

/** 播放暂停按钮 */
@property (nonatomic,strong) UIButton * playBtn;

/** 是否全屏 */
@property (nonatomic) BOOL isFullScreen;

/** 是否播放 */
@property (nonatomic) BOOL isPlay;

@end

@implementation CIBNPlayController

- (void)viewDidLoad {
    [super viewDidLoad];

    
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 通知监听
    [self setNotifi];
    // 获取数据
    [self loadPlayData:self.model.contentid];
    
    [self loadLikeData:self.model.contentid];
    
    // 创建视图
    [self createCollectionView];
    
    // 创建播放器
    [self createPlayer];
    // 创建按钮
    [self createItem];
}
- (void)createCollectionView{
    
    self.sectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 30)];
    self.sectionLabel.font = [UIFont systemFontOfSize:14];
    self.sectionLabel.backgroundColor = [UIColor whiteColor];
    
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
    layout.headerReferenceSize = CGSizeMake(ScreenWidth, 40);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, ScreenWidth*9/16, ScreenWidth, ScreenHeight - (ScreenWidth*9/16)) collectionViewLayout:layout];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    [self.collectionView registerClass:[CIBNPlayTitleCell class] forCellWithReuseIdentifier:titleCell];
    [self.collectionView registerClass:[CIBNCellRelatedCell class] forCellWithReuseIdentifier:relatedCell];
    [self.collectionView registerClass:[CIBNActorCell class] forCellWithReuseIdentifier:ActorCell];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header1"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header2"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header3"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header4"];
    [self.view addSubview:self.collectionView];
    

    
    
}
#pragma mark - UICollectionViewFlowLayoutDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 0:
        {
            CGFloat h = [ZJModelTool sizeWithText:self.playDataModel.storyplot font:[UIFont systemFontOfSize:14] width:ScreenWidth - 20];
            return CGSizeMake(ScreenWidth, h + 40);
        }
            break;
            
        case 1:
        {
            return CGSizeMake(ScreenWidth, ((ScreenWidth - 50)/5) + 20);
        }
            break;
        case 2:
        {
            return CGSizeMake((ScreenWidth - 40) /3, (((ScreenWidth - 40) /3) * 16/9) + 20);
        }
            break;
        default:
        {
            return CGSizeMake(ScreenWidth, 100);
        }
            break;
    }
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    switch (section) {
        case 0:
        {
            return UIEdgeInsetsMake(10, 0, 0, 0);
        }
            break;
            
        case 1:
        {
            return UIEdgeInsetsMake(10, 0, 0, 0);
        }
            break;
        case 2:
        {
            return UIEdgeInsetsMake(10, 5, 10, 5);
        }
            break;
        default:
        {
            return UIEdgeInsetsMake(10, 0, 0, 0);
        }
            break;
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 4;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    switch (section) {
        case 0:
        {
            return 1;
        }
            break;
            
        case 1:
        {
            NSMutableArray * arr = [[NSMutableArray alloc] init];
            NSMutableArray * arr2 = [[NSMutableArray alloc] init];
            if (self.playDataModel.actor == nil) {
                arr = [[self.playDataModel.actor componentsSeparatedByString:@";"] mutableCopy];
//                [arr removeObject:@""];
            }
            if (self.playDataModel.director == nil) {
                arr2 = [[self.playDataModel.director componentsSeparatedByString:@";"] mutableCopy];
//                [arr2 removeObject:@""];
            }
            
            return 1;
        }
            break;
        case 2:
        {
            return 6;
        }
            break;
        default:
        {
            return 1;
        }
            break;
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    switch (indexPath.section) {
        case 0:
        {
            UICollectionReusableView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                                       withReuseIdentifier:@"header1"
                                                                                              forIndexPath:indexPath];
            UILabel * section = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 30)];
            section.font = [UIFont systemFontOfSize:14];
            section.backgroundColor = [UIColor whiteColor];
            
            headerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            
            section.text = [NSString stringWithFormat:@"  %@ (%@) %.1f分",self.playDataModel.vname, self.playDataModel.issueyear, [self.playDataModel.score floatValue]/10];
            [headerView addSubview:section];
            return headerView;
        }
            break;
        case 1:
        {
            UICollectionReusableView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                                       withReuseIdentifier:@"header2"
                                                                                              forIndexPath:indexPath];
            UILabel * section = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 30)];
            section.font = [UIFont systemFontOfSize:14];
            section.backgroundColor = [UIColor whiteColor];
            
            headerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            section.text = @"  演员导演";
            [headerView addSubview:section];
            return headerView;
        }
            break;
        case 2:
        {
            UICollectionReusableView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                                       withReuseIdentifier:@"header3"
                                                                                              forIndexPath:indexPath];
            
            UILabel * section = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 30)];
            section.font = [UIFont systemFontOfSize:14];
            section.backgroundColor = [UIColor whiteColor];
            headerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
            section.text = @"  猜你喜欢";
            [headerView addSubview:section];
            return headerView;
            
        }
            break;
        default:
        {
            UICollectionReusableView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader
                                                                                       withReuseIdentifier:@"header4"
                                                                                              forIndexPath:indexPath];
            
            UILabel * section = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, ScreenWidth, 30)];
            section.font = [UIFont systemFontOfSize:14];
            section.backgroundColor = [UIColor whiteColor];
            headerView.backgroundColor = [UIColor groupTableViewBackgroundColor];
             section.text = @"  评论";
            [headerView addSubview:section];
            return headerView;
           
        }
            break;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
   
    switch (indexPath.section) {
        case 0:
        {
            CIBNPlayTitleCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:titleCell forIndexPath:indexPath];
            [cell setCellModel:self.playDataModel];
            return cell;
        }
            break;
        case 1:
        {
            CIBNActorCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:ActorCell forIndexPath:indexPath];
            [cell setCellsModel:self.playDataModel];
            return cell;
        }
            break;
        case 2:
        {
            CIBNCellRelatedCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:relatedCell forIndexPath:indexPath];
            
            CIBNRelatedVideoModel * model = self.likeDataArray[indexPath.row];
            
            [cell setHomeCell:model];
            return cell;
        }
            break;
            
        default:
        {
            UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
            cell.backgroundColor = [UIColor yellowColor];
            
            return cell;
        }
            break;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 2:
        {
            CIBNRelatedVideoModel * model = self.likeDataArray[indexPath.row];
            [self loadPlayData:model.VID];
            [self loadLikeData:model.VID];
        }
            break;
            
        default:
            break;
    }
}


#pragma mark - 创建播放器
- (void)createPlayer{
    self.playManager = [[CIBNAVPlayerManager alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenWidth*9/16)];
    [self.view addSubview:self.playManager];
}

#pragma mark - 获取播放页数据
- (void)loadPlayData:(NSString *)vid{
    
    self.playDataModel = nil;
    
    [RJNetwoking POST:Domain_URL body:@{
                                        @"Cmdid":@"4657",
                                        @"Seqid":@"536",
                                        @"ProtoVer":@"1",
                                        @"UID":@"24402",
                                        @"HID":@"049364046517234524AF2C911F6D5228",
                                        @"TID":@"42756", 
                                        @"CliVer":@"72058693549555712", 
                                        @"Oemid":@"10001",
                                        @"Epgid":@"9",
                                        @"Sessid":@"4932576889038009721",
                                        @"TermType":@"30", 
                                        @"VId":vid
                                        }
              success:^(id  _Null_unspecified responseObject) {
                  
                  if ([responseObject[@"Status"] integerValue] == 0) {
                      // 字典中有数组字典 转模型
                      [CIBNPlayHomeModel mj_setupObjectClassInArray:^NSDictionary *{
                          return @{@"EpisodeList":@"CIBNEpisodeListModel"};
                      }];
                      
                      self.playDataModel = [CIBNPlayHomeModel mj_objectWithKeyValues:responseObject];
                      
                      
                      
                      // 根据获取到得数据中得SID 获取视频播放地址
                      [self loadVideoData:vid];
                  }
                  
                  
              } failure:^(NSError * _Nonnull error) {
                  
              }];
}
#pragma mark - 获取播放地址
- (void)loadVideoData:(NSString *)vid{
    
    [self.videoDataArray removeAllObjects];
    
    CIBNEpisodeListModel * episodeListModel = self.playDataModel.EpisodeList[1];
    NSLog(@"---%@",episodeListModel.SID);
    
    [RJNetwoking POST:Domain_URL body:@{
                                        @"Cmdid":@"4644",
                                        @"Seqid":@"64",
                                        @"ProtoVer":@"1",
                                        @"UID":@"24402",
                                        @"HID":@"56D7A9EA3A70EC3618391BA1A3CB59EE",
                                        @"TID":@"52490",
                                        @"CliVer":@"72058693549555712",
                                        @"Oemid":@"10001",
                                        @"Epgid":@"9",
                                        @"Sessid":@"7971748004975592437",
                                        @"TermType":@"30",
                                        @"VID":vid,
                                        @"SID":episodeListModel.SID
                                        }
              success:^(id  _Null_unspecified responseObject) {
                  
                  if ([responseObject[@"Status"] integerValue] == 0 && [responseObject[@"CurNum"] integerValue] > 0) {
                      
                      self.videoDataArray = [CIBNVideoModel mj_objectArrayWithKeyValuesArray:responseObject[@"FidList"]];
                      
                      CIBNVideoModel * model = self.videoDataArray[0];
                      NSLog(@"%@%@",model.fid,model.secert);
                      
                      if (model.fid != nil && model.secert != nil) {
                          [self.playManager setVideoUrl:[NSString stringWithFormat:@"%@%@",model.fid,model.secert]];
                          [self.playManager videoPlay];
                      }
                  }
                  
                  [self.collectionView reloadData];
                  
              } failure:^(NSError * _Nonnull error) {
                  
              }];
}

#pragma mark - 获取喜欢数据
- (void)loadLikeData:(NSString *)vid{
    [RJNetwoking POST:Domain_URL body:@{
                                        @"Cmdid":@"4642",
                                        @"Seqid":@"538",
                                        @"ProtoVer":@"1",
                                        @"UID":@"24402",
                                        @"HID":@"049364046517234524AF2C911F6D5228",
                                        @"TID":@"42756",
                                        @"CliVer":@"72058693549555712",
                                        @"Oemid":@"10001",
                                        @"Epgid":@"9",
                                        @"Sessid":@"4932576889038009721",
                                        @"TermType":@"30",
                                        @"Vid":vid,
                                        @"StartIndex":@"0",
                                        @"GetNum":@"50"
                                        
                                        }
              success:^(id  _Null_unspecified responseObject) {
                  
                  if ([responseObject[@"Status"] integerValue] == 0 && [responseObject[@"CurNum"] integerValue] > 0) {
                      
                      self.likeDataArray = [CIBNRelatedVideoModel mj_objectArrayWithKeyValuesArray:responseObject[@"RelatedVideoList"]];
                  }
                  
                  [self.collectionView reloadData];
                  
              } failure:^(NSError * _Nonnull error) {
                  
              }];
}

#pragma mark - 创建返回按钮
- (void)createItem{
    
    UIButton * back = [[UIButton alloc] initWithFrame:CGRectMake(5, 12, 40, 40)];
    [back setImage:[UIImage imageNamed:@"movie_back_s"] forState:UIControlStateNormal];
    [self.view addSubview:back];
    [back addTarget:self action:@selector(backItemClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.isFullScreen = YES;
    self.fullScreenBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 50, (ScreenWidth *9/16) - 50, 40, 40)];
    [self.fullScreenBtn setImage:[UIImage imageNamed:@"movie_fullscreen"] forState:UIControlStateNormal];
    [self.view addSubview:self.fullScreenBtn];
    [self.fullScreenBtn addTarget:self action:@selector(fullScreenBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
    self.isPlay = YES;
    self.playBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, (ScreenWidth *9/16) - 50, 40, 40)];
    [self.playBtn setImage: [UIImage imageNamed:@"movie_pause"] forState:UIControlStateNormal];
    [self.view addSubview:self.playBtn];
    [self.playBtn addTarget:self action:@selector(playBtnClick) forControlEvents:UIControlEventTouchUpInside];
    
}
#pragma mark - 播放暂停按钮事件
- (void)playBtnClick{
    if (self.isPlay == YES) { // 暂停
        self.isPlay = NO;
        [self.playBtn setImage:[UIImage imageNamed:@"movie_play"] forState:UIControlStateNormal];
        [self.playManager videoPause];
        
    }else{ // 播放
        self.isPlay = YES;
        [self.playBtn setImage:[UIImage imageNamed:@"movie_pause"] forState:UIControlStateNormal];
        [self.playManager videoPlay];
    }
}

#pragma mark - 全屏按钮事件
- (void)fullScreenBtnClick{
    
    if (self.isFullScreen == YES) {
        
        [self fullScreen:0];
    }
    else{
        [self miniScreen:0];
    }
}

#pragma mark - 全屏 小屏 cureentInterfaceOrientation --> 0 为点击全屏按钮   1 为手动旋转手机
- (void)fullScreen:(NSUInteger)cureentInterfaceOrientation{
    
    if (cureentInterfaceOrientation == 0) {    // 转屏
        [InterfacOrientation setInterfacOrientation:UIInterfaceOrientationLandscapeLeft];
    }
    self.isFullScreen = NO;
    [self.fullScreenBtn setImage:[UIImage imageNamed:@"movie_mini"] forState:UIControlStateNormal];
    self.playBtn.frame = CGRectMake(10, ScreenHeight - 50, 40, 40);
    self.playManager.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    self.fullScreenBtn.frame = CGRectMake(ScreenWidth - 50, ScreenHeight - 50, 40, 40);
    
    [self.playManager isfulScreen];
}

- (void)miniScreen:(NSUInteger)cureentInterfaceOrientation{
    
    if (cureentInterfaceOrientation == 0) {
        [InterfacOrientation setInterfacOrientation:UIInterfaceOrientationPortrait];
    }
    self.isFullScreen = YES;
    [self.fullScreenBtn setImage:[UIImage imageNamed:@"movie_fullscreen"] forState:UIControlStateNormal];
    self.playBtn.frame = CGRectMake(10, (ScreenWidth*9/16) - 50, 40, 40);
    self.playManager.frame = CGRectMake(0, 0, ScreenWidth, ScreenWidth*9/16);
    self.fullScreenBtn.frame = CGRectMake(ScreenWidth - 50, (ScreenWidth*9/16) - 50, 40, 40);
    
    [self.playManager isfulScreen];
}

#pragma mark - 返回
- (void)backItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 即将显示时隐藏标签栏
- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.InterfaceOrientation = 1;
}

- (void)viewDidDisappear:(BOOL)animated{
    [self.playManager videoPause];
    self.playManager = nil;
    AppDelegate * delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    delegate.InterfaceOrientation = 0;
}
#pragma mark - 隐藏状态栏
- (BOOL)prefersStatusBarHidden{
    return YES;
}

#pragma mark - 设置通知监听
- (void)setNotifi{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(interfaceOrientation:) name:UIDeviceOrientationDidChangeNotification object:nil];
}

- (void)interfaceOrientation:(NSNotification *)noti{
    NSLog(@"%@--%f--%f",noti.userInfo,ScreenWidth,ScreenHeight);
    
    if (ScreenWidth > ScreenHeight) {// 横屏
        [self fullScreen:1];
    }
    else{// 竖屏
        [self miniScreen:1];
    }
}
@end
